<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionBack\Controller;

use AuctionBack\Logic\OrderLogic;
use AuctionCore\Account\Back\Employee;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\AuctionOrder\AuOrderList as AuOrderList;
use AuctionCore\CarResource\Car;
use AuctionCore\System\AuctionException;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\Cashier\Collection;
use AuctionCore\CarDealer\Dealer;

/**
 * 拍品查询
 *
 * @author Xmh
 */
class OrderCheckController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
        //模板赋值
        $this->assign("emp_id", $this->emp_id);

        $order_pay_status = C('ORDER_PAY_STATUS');
        unset($order_pay_status[0]);
        $this->assign('order_pay_status', $order_pay_status);
    }

    /**
     * 拍品查询列表
     */
    public function index()
    {
        //获取父级渠道来源
        $pfrom = M("come_from")->where("pid=-2 AND is_delete=0")->select();
        //获取渠道来源列表
        $cols = 'a.from_id,a.from_name,b.from_name AS pname,b.from_id AS pid,b.sort AS psort';
        $condition['a.pid'] = array('neq', '-2');
        $condition['a.is_delete'] = array('eq', '0');
//        $condition['a.from_id'] = array('neq', '-1');
        $order = 'psort ASC,from_id ASC,pid DESC';
        $from = M("come_from")->alias('a')
            ->join('INNER JOIN (SELECT from_id,from_name,sort FROM au_come_from WHERE pid=-2 AND is_delete=0) AS b ON a.pid=b.from_id')
            ->field($cols)
            ->where($condition)
            ->order($order)
            ->select();
        $this->assign('from', $from);
        $this->assign('pfrom', $pfrom);

        $branch_id = $this->user_info['branch_id'];
        //分公司列表
        $bc_list = $this->get_branch_company_list();
        $this->assign('bc_list', $bc_list);
        $this->assign('branch_id', $branch_id);


        $comefrom_list = $this->get_comefrom_list();
        //城市对应的4s店
        $bc_city = $this->bc_city;
        $city_fours_list = array();
        foreach ($bc_city as $kb => $vb) {
            $city_fours = M("come_from")->alias('a')->field('a.from_id,a.from_name')
                ->join(C('DB_PREFIX') . 'fours as f ON a.from_id = f.channel_id')
                ->where(array('f.city' => $kb))
                ->order('from_id ASC,pid DESC')
                ->select();
            $city_fours_list[$kb] = $city_fours;
        }
        $this->assign('comefrom_list', $comefrom_list);
        $this->assign('city_fours_list', $city_fours_list);
        $this->display();
    }

    /**
     * 拍品查询列表数据
     */
    public function order_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['time_mode'] = I('get.time_mode/d', 0);
        $params['start_time'] = I('get.start_time');
        $params['end_time'] = I('get.end_time');
        $params['order_status'] = I('get.order_status/d');              //车辆状态
        $params['pay_status'] = I('get.pay_status/d');              //付款状态
        $params['location_area'] = I('get.location_area');          //车辆所在地
        $params['comefrom'] = I('get.comefrom', -2);                //车辆来源
        $params['order_no'] = I('get.order_no');                        //车辆编号
        $params['car_level'] = I('get.car_level');                  //车辆等级
        $params['car_plate_number'] = I('get.car_plate_number');    //车牌号
        //$params['car_vin'] = I('get.car_vin');                      //车架号
        $params['emp_id'] = $this->emp_id;

        //所在地查询
        if (count($this->bc_city) > 1) {
            $bc_code = array_flip($this->bc_city);
            $bc_code = implode(',', $bc_code);
            $params['bc_city'] = $bc_code;
        }
        //检查权限
        $rules = "CheZhuQueRenChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $auth = $e->check_auth($rules);
        $params['auth'] = $auth;
        //获取list
        $cl = new AuOrderList();
        $result = $cl->get_order_list($page, $size, $params);
        $list = empty($result['list']) ? array() : $result['list'];
        //分页
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %nextPage% %downPage%  %end% %jumpform%");
//        dump($list);
        $show = $Page->show();          // 分页显示输出
        $this->assign('page', $show);   // 赋值分页输出
        $this->assign('list', $list);
        $this->assign('p', $page);
        $this->assign('total', $result['total']);
        $show_from = $this->get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $this->display();
    }

    /**
     * 拍品查询列表数据
     */
    public function export_order_list()
    {
        $params = array();
        $params['start_time'] = I('get.start_time');
        $params['end_time'] = I('get.end_time');
        $params['order_status'] = I('get.order_status/d');              //车辆状态
        $params['comefrom'] = I('get.comefrom', -2);                //车辆来源
        $params['order_no'] = I('get.order_no');                        //车辆编号
        $params['car_level'] = I('get.car_level');                  //车辆等级
        $params['car_plate_number'] = I('get.car_plate_number');    //车牌号
        $params['emp_id'] = $this->emp_id;
        //获取list
        $cl = new AuOrderList();
        $result = $cl->get_export_order_list($params);
        $list = empty($result['list']) ? array() : $result['list'];
        if (empty($list)) {
            $this->helpJsonResult(400, '没有数据');
        }
        $cm = new \AuctionCore\CarResource\CarModel();
        $list_data = array();
        foreach ($list as $k => $v) {
            $owner = new \AuctionCore\CarOwner\Owner($v['owner_id']);
            $owner_detail = $owner->detail();
            $list_data[$k]['check_date'] = date("Y年m月d日", strtotime($v['check_date']));
            $list_data[$k]['bidding_start_time'] = $v['bidding_start_time'];
            $show_from = $this->get_from();  //获取渠道来源信息
            $comefrom = M("car_owner")->alias("a")
                ->join('INNER JOIN ' . C('DB_PREFIX') . 'cars AS b ON a.owner_id=b.owner_id')
                ->field('comefrom')
                ->where('b.car_id=' . $v['car_id'])
                ->find();
            $list_data[$k]['comefrom'] = $show_from[$comefrom['comefrom']];
            $list_data[$k]['seller_name'] = $owner_detail['seller_name'];
            $list_data[$k]['seller_phone'] = $owner_detail['phone'];
            $brand = $cm->get_model_by_id($v['brand_id'], 'brand');
            $series = $cm->get_model_by_id($v['series_id'], 'series');
            $model = $cm->get_model_by_id($v['model_id']);
            $list_data[$k]['car_model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
            //$car = M('cars')->field('first_reg_date,pointer_mileage,reg_city,emission,composite_state,accident_level,car_color,transfer_times')->where(array('car_id' => $v['car_id']))->find();
            $list_data[$k]['first_reg_date'] = date("Y年m月d日", strtotime($v['first_reg_date']));
            $list_data[$k]['pointer_mileage'] = sprintf("%.2f", $v['pointer_mileage'] / 10000) . "万公里";
            $list_data[$k]['transfer_times'] = $v['transfer_times'];
            $list_data[$k]['car_level'] = $v['composite_state'] . $v['accident_level'];
            $perfrom = M('car_perform')->where("car_id='" . $v['car_id'] . "'")->find();
            $list_data[$k]['car_remark'] = $perfrom['other_info'] ? $perfrom['other_info'] : "无";

//            $a = new \AuctionCore\Other\Address();
//            $area = $a->get_province($v['reg_city']);
//            $province = $area['province'];
//            $city = $area['city_name'];
//            $reg_city = $a->get_name_by_code($car['reg_city']);
//            $list_data[$k]['reg_city'] = $province . " " . $city;
//            $list_data[$k]['mession'] = C('EMISSION.' . $v['emission']);
//            $list_data[$k]['color'] = C('CAR_COLOR.' . $v['car_color']);
        }
        $export = new \AuctionCore\Other\Export();
        $title = array('检测日期', '上拍日期', '渠道来源', '客户姓名', '客户电话', '车型', '初登日期', '表显里程', '过户次数', '车辆等级', '车辆补充说明'); //, '注册地', '排放标准', '颜色'
        $export->output_csv($list_data, $title);
    }

    /**
     * 拍单详情
     */
    public function order_info()
    {
        $order_id = I('get.id/d');
        if ($order_id) {
            $order = AuOrder::get_order_and_scene($order_id);
            $car = M('cars')->alias('c')->field('c.*,co.comefrom,co.comefrom_url')
                ->join(C('DB_PREFIX') . "car_owner as co ON c.`owner_id`=co.`owner_id`")
                ->where(array('car_id' => $order['car_id']))->find();
            $order_info = array();
            $order_info['order_no'] = $order['order_no'];
            $order_info['is_other_channel_deal'] = $order['is_other_channel_deal'];
            //$order['is_other_channel_deal'] = $vo['is_other_channel_deal'];//是否其他渠道成交
            if ($order['is_other_channel_deal'] == 1) { //是否其他渠道成交
                $isSelfReceive = $car['is_self_receive'];
                $orderId = $order['order_id'];
                $map['order_id'] = $orderId;
                $map['payment_type'] = 1; //1 应收车款
                $auorderObj = new AuOrder($orderId);
                $collectionOrderInfo = $auorderObj->getCollectionOrderRelationByCondition($map);

                $colletionId = $collectionOrderInfo['collection_id'];
                $collectionInfo = Collection::getInfoById($colletionId);

                $sid = $car['sid'];
                $purchaseOrderObj = new PurchaseOrder();
                $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);

                if ($isSelfReceive == 1) { //如果是自收车辆
                    $selfObj = new SelfReceiveCar();
                    $selfCarData = $selfObj->getInfoByOtherOrderId($orderId);
                    $order_info['order_amount'] = $selfCarData['trade_price']; //订单金额
                    $order_info['transfer_fee'] = $selfCarData['transfer_fee']; // 交付服务费
                    $order_info['modify_no'] = ''; //变更单号
                    $order_info['purchase_order_nu'] = $purchaseOrderData['purchase_order_nu']; //采购单编号
                    $order_info['create_time'] = $order['create_time']; //订单生成时间
                    $order_info['collection_no'] = $collectionInfo['collection_no'];
                } else {
                    $breachCarInfo = BreachCar::getInfoByOtherOrderId($orderId);
                    $order_info['order_amount'] = $breachCarInfo['trade_price']; //订单金额
                    $order_info['transfer_fee'] = $breachCarInfo['transfer_fee']; //交付服务费
                    $mid = $breachCarInfo['mid'];
                    $changeOrderInfo = ChangeOrder::getOneInfo($mid);
                    $order_info['modify_no'] = $changeOrderInfo['modify_no']; //变更单号
                    $order_info['purchase_order_nu'] = $purchaseOrderData['purchase_order_nu']; //采购单编号
                    $order_info['create_time'] = $order['create_time']; //订单生成时间
                    $order_info['collection_no'] = $collectionInfo['collection_no'];
                }
            } else {
                $order_info['scene_name'] = $order['name'];
                $order_info['order_no'] = $order['order_no'];
                $order_info['is_timing_order'] = $order['is_timing_order'];
                $order_info['est_elapsed_time'] = ($order['est_elapsed_time'] / 60) . '分钟';
                $order_info['bidding_start_time'] = date("Y年m月d日 H:i", strtotime($order['bidding_start_time']));
                if ($order['bidding_end_time'] == '0000-00-00 00:00:00') {
                    $bidding_end_time = '竞拍未结束';
                } else {
                    $bidding_end_time = date("Y年m月d日 H:i", strtotime($order['bidding_end_time']));
                }
                $order_info['bidding_end_time'] = $bidding_end_time;
                $order_info['bid_start_price'] = format_money($order['bid_start_price']) . '元';
                $order_info['coupon'] = $order['coupon'] . '元';
                $order_info['reserve_price'] = format_money($order['reserve_price']) . '元';
                $order_info['show_reserve_price'] = $order['show_reserve_price'];
                $order_info['commision'] = $order['commision'] . '元';
                $order_info['transfer_fee'] = $order['transfer_type']==1 ? "--" : $order['transfer_fee'] . '元'; //车商自过不收手续费
                if ($order['bidding_best_price'] > $order['bid_best_price']) {
                    $best_price = $order['bidding_best_price'];
                } else {
                    $best_price = $order['bid_best_price'];
                }
                $order_info['bidding_best_price'] = format_money($best_price) . '元';
                //拍单状态
                $fail_type = $order['fail_type'];
                $status = $order['status'];
                if ($status == 5) {
                    $status_code = 5;
                } elseif ($status == 12 && $fail_type == 2 && $order['is_consult'] == 0) { //确认失败
                    $status_code = 52;
                } elseif ($status == 12 && ($fail_type == 1 || $fail_type == 6)) { //拍单流拍（重拍）
                    $status_code = 6;
                } elseif ($order['is_consult'] == 1 && $order['consult_status'] == 5) {
                    $status_code = 61;
                } elseif ($status == 7 && ($order['return_check_status'] == 5 || $order['return_check_status'] == 7)) {  //待签约
                    $status_code = 7;
                } elseif ($status == 12 && $fail_type == 3) {   //签约失败
                    $status_code = 71;
                } elseif ($status == 8 && $order['return_check_status'] == 1 && $order['crl_status'] == 0) { //待回车
                    $status_code = 81;
                } elseif ($status == 8 && $order['return_check_status'] == 2) {    //回车中
                    $status_code = 82;
                } elseif (($status == 7 || $status == 8) && ($order['arc_status'] == 0 || $order['arc_status'] == 1) && ($order['return_check_status'] == 3 || $order['return_check_status'] == 4)) { //待复检
                    $status_code = 83;
                } elseif ($status == 8 && ($order['cdc_status'] == 0 || $order['cdc_status'] == 1)
                    && ($order['check_car_status'] == 1 || $order['check_car_status'] == 2)
                ) {   //待验车
                    $status_code = 84;
                } elseif ($status == 8 && $order['check_car_status'] == 3 && $car['pay_status'] == 1) {   //已验车 -- 杭州
                    $status_code = 841;
                } elseif ($status == 8 && $order['dealer_pay_status'] == 0) {
                    $status_code = 849;
                } elseif ($status == 8 && ($order['dealer_pay_status'] == 1 || $order['dealer_pay_status'] == 2)) { //待收款
                    $status_code = 85;
                } elseif ($status == 8 && $order['delivery_mode'] == 2 &&
                    $order['dealer_pay_status'] == 3 && $order['first_pay_status'] == 0
                ) { //已收款 --北京
                    $status_code = 851;
                } elseif (!is_null($order['oi_status']) && $order['oi_status'] == 0) {    //车主待争议
                    $status_code = 86;
                } elseif ($order['is_lock'] == 1) {
                    $status_code = 862;
                } elseif ($order['oi_status'] == 2) {    //车主协商失败
                    $status_code = 861;
                } elseif (!is_null($order['di_status']) && $order['di_status'] == 0) {    //车商待争议
                    $status_code = 87;
                } elseif ($status == 12 && ($order['dealer_issue_status'] == 3 || $order['dealer_issue_status'] == 4)) {    //车商协商失败
                    $status_code = 871;
                } elseif ($status == 12 && $order['fail_type'] == 9) {  //平台确认失败
                    $status_code = 119;
                } elseif ($status == 12 && $order['fail_type'] == 10) { //自收完成导致失败的拍单
                    $status_code = 1210;
                } else {
                    $status_code = $status;
                }
                //是否显示
                $order_info['order_status_name'] = C('ORDER_STATUS')[$status_code];
                $order_info['order_status'] = $order['status'];
                $order_info['fail_type'] = $fail_type;
                $order_info['consult_status'] = $order['consult_status'] ? $order['consult_status'] : 0;
                $order_info['is_consult'] = $order['is_consult'];
                $order_info['success_price'] = $order['success_price'];
                $order_info['company_subsidies'] = $order['company_subsidies'];
            }
            $cm = new \AuctionCore\CarResource\CarModel();
            $brand = $cm->get_model_by_id($car['brand_id'], 'brand');
            $series = $cm->get_model_by_id($car['series_id'], 'series');
            $model = $cm->get_model_by_id($car['model_id']);
            $model_show = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
            $car_info = array();
            $car_info['car_id'] = $car['car_id'];
            $car_info['car_no'] = $car['car_no'];
            $car_info['car_source_nu'] = $car['sno'];
            $car_info['car_status'] = $car['car_status'];
            $car_info['model'] = $model_show ? $model_show : $car['car_model'];
            $car_info['mession'] = C('EMISSION.' . $car['emission']);
            $car_info['first_reg_date'] = date("Y年m月d日", strtotime($car['first_reg_date']));
            $car_info['color'] = C('CAR_COLOR.' . $car['car_color']);
            $car_info['pointer_mileage'] = formatMileage($car['pointer_mileage']); //round(/10000,2)>1?round($car['pointer_mileage']/10000,2):$car['pointer_mileage'];
            $car_info['car_level'] = $car['composite_state'] . $car['accident_level'];

            $a = new \AuctionCore\Other\Address();
            $area = $a->get_province($car['reg_city']);
            $province = $area['province'];
            $city = $area['city_name'];
            $reg_city = $a->get_name_by_code($car['reg_city']);
            $location_area = $a->get_name_by_code($car['location_area']);;
            $car_info['location_area'] = $location_area;
            $car_info['reg_city'] = $province . " " . $city;
            $car_info['car_plate_number'] = C('PLATE_PREFIX.' . $car['plate_prefix']) . $car['plate_suffix'];
            $car_info['car_vin'] = $car['vin'];
            $car_info['suggest_max_price'] = format_money($car['suggest_max_price']);
            $car_info['suggest_min_price'] = format_money($car['suggest_min_price']);
            $car_info['suggest_bid_start_price'] = format_money($car['suggest_bid_start_price']);
            $car_info['transfer_limit'] = $car['transfer_limit'];
            $car_info['comefrom'] = $car['comefrom'];
            $car_info['comefrom_url'] = $car['comefrom_url'];

            $owner = M('car_owner')->field('seller_name,phone,owner_type,contact_person')
                ->where(array('owner_id' => $car['owner_id']))
                ->find();
            $owner['owner_type_name'] = C('OWNER_TYPE_NAME')[$owner['owner_type']];
            $this->assign('owner', $owner);
            $this->assign("car_info", $car_info);
            $this->assign('order_info', $order_info);
        } else {
            $this->helpJsonResult(400, '没有此拍品！');
        }

        /**
         * 投标价格 - 竞拍价格 - 出价历史
         */
        $bid_log = M('bid_log')->alias('bl')
            ->field('bl.bid_id,bl.bid_type,bl.price,bl.createtime,cd.contact_person,du.uid')
            ->join(C('DB_PREFIX') . "car_dealer as cd ON bl.dealer_id=cd.dealer_id")
            ->join(C('DB_PREFIX') . "dealer_user as du ON du.dealer_id=cd.dealer_id")
            ->where(array('order_id' => $order_id))
            ->select();
        if (!empty($bid_log)) {
            $dealer = new Dealer();
            $bid_log = $dealer->get_contact_mobile_byAntNest($bid_log);
        }
        //echo M()->getLastSql();
        $bid_log_list = array();
        if (array_filter($bid_log)) {
            foreach ($bid_log as $kbi => $vbi) {
                $bid_log_list[$kbi]['bid_id'] = $vbi['bid_id'];
                $bid_log_list[$kbi]['consult_type'] = $vbi['bid_type'];
                $bid_log_list[$kbi]['price'] = $vbi['price'];
                $bid_log_list[$kbi]['createtime'] = $vbi['createtime'];
                $bid_log_list[$kbi]['dealer_name'] = $vbi['contact_person'];
                $bid_log_list[$kbi]['contact_mobile'] = $vbi['contact_mobile'];
                $bid_log_list[$kbi]['type'] = 1;
            }
        }
        $bidding_log = M('bidding_log')->alias('bl')
            ->field('bl.bidding_id,bl.bidding_type,bl.after_price,bl.createtime,bl.is_auto,cd.contact_person,du.uid')
            ->join(C('DB_PREFIX') . "car_dealer as cd ON bl.dealer_id=cd.dealer_id")
            ->join(C('DB_PREFIX') . "dealer_user as du ON du.dealer_id=cd.dealer_id")
            ->where(array('order_id' => $order_id))
            ->select();
        if (!empty($bidding_log)) {
            $dealer = new Dealer();
            $bidding_log = $dealer->get_contact_mobile_byAntNest($bidding_log);
        }
//        echo M()->getLastSql();
        $bidding_log_list = array();
        if (array_filter($bidding_log)) {
            foreach ($bidding_log as $kbd => $vbd) {
                $bidding_log_list[$kbd]['bidding_id'] = $vbd['bidding_id'];
                $bidding_log_list[$kbd]['consult_type'] = $vbd['bidding_type'];
                $bidding_log_list[$kbd]['price'] = $vbd['after_price'];
                $bidding_log_list[$kbd]['dealer_name'] = $vbd['contact_person'];
                $bidding_log_list[$kbd]['contact_mobile'] = $vbd['contact_mobile'];
                $bidding_log_list[$kbd]['createtime'] = $vbd['createtime'];
                $bidding_log_list[$kbd]['type'] = 2;
                $bidding_log_list[$kbd]['is_auto'] = $vbd['is_auto'];
            }
        }
//        dump($bidding_log_list);
        $bid_history = array();
        if (array_filter($bid_log_list)) {
            $bid_history = $this->bid_history_sort($bid_log_list, 'bid_id');
        }
        if (array_filter($bidding_log_list)) {
            $bid_history = $this->bid_history_sort($bidding_log_list, 'bidding_id');
        }
        if (array_filter($bid_log) && array_filter($bidding_log)) {
            $bid_history_list = $this->bid_history_sort($bid_log_list, 'bid_id');
            $bidding_history_list = $this->bid_history_sort($bidding_log_list, 'bidding_id');
            $bid_history = array_merge($bidding_history_list, $bid_history_list);
        }
        if (array_filter($bid_history)) {
            $i = 1;
            $bid_history_list = array();
            foreach ($bid_history as $k => $v) {
                $bid_history_list[$k]['sort'] = $i;
                $bid_history_list[$k]['consult_type'] = $v['consult_type'];
                $bid_history_list[$k]['price'] = format_money($v['price']);
                $bid_history_list[$k]['createtime'] = date("Y.m.d H:i:s", strtotime($v['createtime']));
                $bid_history_list[$k]['dealer_name'] = $v['dealer_name'];
                $bid_history_list[$k]['contact_mobile'] = $v['contact_mobile'];

                //出价历史：出价方式（智能/手动）
                //2016-11-28    by:shaoshuai
                if ($v['is_auto'] == 1) {
                    $bid_history_list[$k]['type'] = 3;
                } else {
                    $bid_history_list[$k]['type'] = $v['type'];
                }

                $i++;
            }
        }
//        dump($bid_history_list);
        $this->assign('bid_history_list', $bid_history_list);


        /**
         * 投标价格 - 竞拍价格 - 出价排名
         */
        $bid_sub_query = M('bid_log')
            ->where(array('order_id' => $order_id))
            ->order('bid_id desc')->buildSql();
        $bid_log_rank = M()->table($bid_sub_query . ' bl')
            ->field('bl.dealer_id,bl.bid_type,bl.price,bl.createtime,cd.contact_person,du.uid')
            ->join(C('DB_PREFIX') . "car_dealer as cd ON bl.dealer_id=cd.dealer_id")
            ->join(C('DB_PREFIX') . "dealer_user as du ON du.dealer_id=cd.dealer_id")
            ->group('bl.dealer_id')
            ->where(array('order_id' => $order_id))
            ->select();
        if (!empty($bid_log_rank)) {
            $dealer = new Dealer();
            $bid_log_rank = $dealer->get_contact_mobile_byAntNest($bid_log_rank);
        }
//        echo M()->getLastSql();
        $bid_log_rank_list = array();
        if (array_filter($bid_log_rank)) {
            foreach ($bid_log_rank as $kbi => $vbi) {
                $bid_log_rank_list[$kbi]['dealer_id'] = $vbi['dealer_id'];
                $bid_log_rank_list[$kbi]['consult_type'] = $vbi['bid_type'];
                $bid_log_rank_list[$kbi]['price'] = $vbi['price'];
                $bid_log_rank_list[$kbi]['createtime'] = $vbi['createtime'];
                $bid_log_rank_list[$kbi]['dealer_name'] = $vbi['contact_person'];
                $bid_log_rank_list[$kbi]['contact_mobile'] = $vbi['contact_mobile'];
                $bid_log_rank_list[$kbi]['type'] = 1;
            }
        }
        $bidding_sub_query = M('bidding_log')
            ->where(array('order_id' => $order_id))
            ->order('bidding_id desc')->buildSql();
        $bidding_log_rank = M()->table($bidding_sub_query . ' bl')
            ->field('bl.dealer_id,bl.bidding_type,bl.after_price,bl.createtime,cd.contact_person,du.uid')
            ->join(C('DB_PREFIX') . "car_dealer as cd ON bl.dealer_id=cd.dealer_id")
            ->join(C('DB_PREFIX') . "dealer_user as du ON du.dealer_id=cd.dealer_id")
            ->group('bl.dealer_id')
            ->where(array('order_id' => $order_id))
            ->select();
        if (!empty($bidding_log_rank)) {
            $dealer = new Dealer();
            $bidding_log_rank = $dealer->get_contact_mobile_byAntNest($bidding_log_rank);
        }
//        echo M()->getLastSql();
        $bidding_log_rank_list = array();
        if (array_filter($bidding_log_rank)) {
            foreach ($bidding_log_rank as $kbd => $vbd) {
                $bidding_log_rank_list[$kbd]['dealer_id'] = $vbd['dealer_id'];
                $bidding_log_rank_list[$kbd]['consult_type'] = $vbd['bidding_type'];
                $bidding_log_rank_list[$kbd]['price'] = $vbd['after_price'];
                $bidding_log_rank_list[$kbd]['dealer_name'] = $vbd['contact_person'];
                $bidding_log_rank_list[$kbd]['contact_mobile'] = $vbd['contact_mobile'];
                $bidding_log_rank_list[$kbd]['createtime'] = $vbd['createtime'];
                $bidding_log_rank_list[$kbd]['type'] = 2;
            }
        }
        $bid_history_rank = array();
        if (array_filter($bid_log_rank_list)) {
            $bid_history_rank = $bid_log_rank_list;
        }
        if (array_filter($bidding_log_rank_list)) {
            $bid_history_rank = $bidding_log_rank_list;
        }
        if (array_filter($bid_log_rank) && array_filter($bidding_log_rank)) {
            $bid_history_rank = array_merge($bid_log_rank_list, $bidding_log_rank_list);
        }
        $bid_history_rank_list = array();
        foreach ($bid_history_rank as $kbhr => $vbhr) {
            if (array_key_exists($vbhr['dealer_id'], $bid_history_rank_list)) {
                if ($bid_history_rank_list[$vbhr['dealer_id']]['price'] > $vbhr['price']) {
                    unset($vbhr);
                } elseif ($bid_history_rank_list[$vbhr['dealer_id']]['price'] == $vbhr['price'] &&
                    $bid_history_rank_list[$vbhr['dealer_id']]['type'] < $vbhr['type']
                ) {
                    unset($vbhr);
                } else {
                    $bid_history_rank_list[$vbhr['dealer_id']] = $vbhr;
                }
            } else {
                $bid_history_rank_list[$vbhr['dealer_id']] = $vbhr;
            }
        }
        $bid_history_rank_data = array_values($this->bid_history_sort($bid_history_rank_list, 'price'));
//        dump($bid_history_rank_data);
        for ($i = 0, $length = count($bid_history_rank_data) - 1; $i < $length; $i++) {
            for ($j = 0; $j < $length - $i; $j++) {
                if ($bid_history_rank_data[$j]['price'] == $bid_history_rank_data[$j + 1]['price']) {
                    if ($bid_history_rank_data[$j]['type'] == $bid_history_rank_data[$j + 1]['type']) {
                        if (strtotime($bid_history_rank_data[$j]['createtime']) > strtotime($bid_history_rank_data[$j + 1]['createtime'])) {
                            $tmp = $bid_history_rank_data[$j];
                            $bid_history_rank_data[$j] = $bid_history_rank_data[$j + 1];
                            $bid_history_rank_data[$j + 1] = $tmp;
                        }
                    } elseif ($bid_history_rank_data[$j]['type'] > $bid_history_rank_data[$j + 1]['type']) {
                        $tmp = $bid_history_rank_data[$j];
                        $bid_history_rank_data[$j] = $bid_history_rank_data[$j + 1];
                        $bid_history_rank_data[$j + 1] = $tmp;
                    }
                }
            }
        }
//        dump($bid_history_rank_data);

        if (array_filter($bid_history_rank_data)) {
            $j = 1;
            $bid_history_rank_list_data = array();
            foreach ($bid_history_rank_data as $k => $v) {
                $bid_history_rank_list_data[$k]['sort'] = $j;
                $bid_history_rank_list_data[$k]['consult_type'] = $v['consult_type'];
                $bid_history_rank_list_data[$k]['price'] = format_money($v['price']);
                $bid_history_rank_list_data[$k]['createtime'] = date("Y.m.d H:i:s", strtotime($v['createtime']));
                $bid_history_rank_list_data[$k]['dealer_name'] = $v['dealer_name'];
                $bid_history_rank_list_data[$k]['contact_mobile'] = $v['contact_mobile'];
                $bid_history_rank_list_data[$k]['type'] = $v['type'];
                $j++;
            }
        }
        $this->assign('bid_history_rank_list_data', $bid_history_rank_list_data);


        /**
         * 拍单状态跟踪日志
         */
        $order_action_log = AuOrder::get_order_trace_log_list($order_id);
        $this->assign('order_action_log', $order_action_log);

        $show_from = $this->get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $this->display();
    }

    /**
     * 出价历史排序
     *
     * @param array $array
     * @param string $key
     * @param string $order
     * @return array
     */
    private function bid_history_sort($array, $key, $order = 'desc')
    {
        $arr_nums = $arr = array();
        foreach ($array as $k => $v) {
            $arr_nums[$k] = $v[$key];
        }
        if ($order == 'desc') {
            arsort($arr_nums);
        } else {
            asort($arr_nums);
        }
        foreach ($arr_nums as $k => $v) {
            $arr[$k] = $array[$k];
        }
        return $arr;
    }

    /**
     * 获取渠道来源信息
     */
    private function get_from()
    {
        $from = M("come_from a")->field("a.from_id,a.from_name,b.from_name AS pname,b.from_id AS pid,b.sort AS psort")
            ->join('(SELECT from_id,from_name,sort FROM au_come_from WHERE pid=-2 AND is_delete=0) AS b ON a.pid=b.from_id')
            ->where("a.pid!=-2 AND a.is_delete=0")
            ->order("psort ASC,pid DESC")
            ->select();
        $show_from = array();
        foreach ($from as $key => $val) {
            $show_from[$val['from_id']] = $val['pname'] . '-' . $val['from_name'];
        }
        return $show_from;
    }

    /**
     * 业务跟踪查询
     */
    public function search()
    {
        $this->display();
    }

    public function records()
    {
        $keyword = I("get.keyword/s", "");
        if (empty($keyword)) {
            $this->helpJsonResult(400, "请输入正确的条件");
        }
        $key_first = strtoupper(mb_substr($keyword, 0, 1, 'utf-8'));
        $show_info = array();
        if ($key_first == "P") { //拍单
            $show_info['type'] = 1;
            try {
                $o = new AuOrder(trim($keyword));
            } catch (AuctionException $e) {
                $this->helpJsonResult(500, $e->getMessage());
            }

            $detail = $o->detail();
            $show_info['no'] = $detail['order_no'];
            $car = new Car($detail['car_id']);
            $car_info = $car->detail();
            $trace_logs = $o::get_order_trace_log_list($detail['order_id']);
            $order = AuOrder::get_order_and_scene($detail['order_id']);;

            //拍单状态
            $fail_type = $order['fail_type'];
            $status = $order['status'];
            if ($status == 5 && $order['owner_confirm_service_id'] == 0) {
                $status_code = 5;
            } elseif ($status == 12 && $fail_type == 2 && $order['is_consult'] == 0) { //确认失败
                $status_code = 52;
            } elseif ($status == 12 && ($fail_type == 1 || $fail_type == 6)) { //拍单流拍（重拍）
                $status_code = 6;
            } elseif ($order['is_consult'] == 1 && $order['consult_status'] == 5) { //磋商失败
                $status_code = 61;
            } elseif ($status == 7 && ($order['return_check_status'] == 5 || $order['return_check_status'] == 7)) {  //待签约
                $status_code = 7;
            } elseif ($status == 12 && $fail_type == 3) {   //签约失败
                $status_code = 71;
            } elseif ($status == 8 && $order['return_check_status'] == 1 && $order['crl_status'] == 0) { //待回车
                $status_code = 81;
            } elseif ($status == 8 && $order['return_check_status'] == 2) {    //回车中
                $status_code = 82;
            } elseif (($status == 7 || $status == 8) && ($order['arc_status'] == 0 || $order['arc_status'] == 1) && ($order['return_check_status'] == 3 || $order['return_check_status'] == 4)) { //待复检
                $status_code = 83;
            } elseif ($status == 8 && ($order['cdc_status'] == 0 || $order['cdc_status'] == 1)
                && ($order['check_car_status'] == 1 || $order['check_car_status'] == 2)
            ) {   //待验车
                $status_code = 84;
            } elseif ($status == 8 && $order['delivery_mode'] == 1
                && $order['check_car_status'] == 3 && $order['first_pay_status'] == 0
            ) {   //已验车 -- 杭州
                $status_code = 841;
            } elseif (($status == 8 && $order['dealer_pay_status'] == 0 && $order['check_car_status'] == 3 && $order['delivery_mode'] == 2) ||
                ($status == 8 && $order['dealer_pay_status'] == 0 && in_array($order['return_check_status'], array(5, 7)) && $order['delivery_mode'] == 1 && $order['car_source'] == 1) ||
                ($status == 8 && $order['dealer_pay_status'] == 0 && $order['delivery_mode'] == 1 && $order['car_source'] == 2)
            ) {
                $status_code = 849;
            } elseif ($status == 8 && ($order['dealer_pay_status'] == 1 || $order['dealer_pay_status'] == 2)) { //待收款
                $status_code = 85;
            } elseif ($status == 8 && $order['location_area'] == '110000' &&
                $order['dealer_pay_status'] == 3 && $order['first_pay_status'] == 0
            ) { //已收款 --北京
                $status_code = 851;
            } elseif (!is_null($order['oi_status']) && $order['oi_status'] == 0) {    //车主待争议
                $status_code = 86;
            } elseif ($order['oi_status'] == 2) {    //车主协商失败
                $status_code = 861;
            } elseif (!is_null($order['di_status']) && $order['di_status'] == 0) {    //车商待争议
                $status_code = 87;
            } elseif ($status == 12 && ($order['dealer_issue_status'] == 3 || $order['dealer_issue_status'] == 4)) {    //车商协商失败
                $status_code = 871;
            } elseif ($status == 12 && $order['fail_type'] == 9) {  //平台确认失败
                $status_code = 119;
            } elseif ($status == 12 && $order['fail_type'] == 10) { //自收完成导致失败的拍单
                $status_code = 12;
            } else {
                $status_code = $status;
            }
            $show_info['status'] = C('ORDER_STATUS')[$status_code];
        } else {
            if ($key_first == "C") {
                $car_info = Car::getCarBySno($keyword);
                if (empty($car_info)) {
                    $this->helpJsonResult('400', '关键词有误');
                }
            } else {
                $plate_prefix = array_search($key_first, C('PLATE_PREFIX'));
                $plate_suffix = mb_substr($keyword, 1, 6, 'utf-8');
                if ($plate_prefix == false) {
                    $this->helpJsonResult(400, "关键词有误");
                }
                $car_info = Car::getCarByPlateNo($plate_prefix, $plate_suffix);

            }
            $detail = OrderLogic::getLatestOrderByCarId($car_info['car_id']);
            $show_info['no'] = $car_info['sno'];
            $show_info['status'] = C("CAR_STATUS." . $car_info['car_status']);
            $trace_logs = Car::get_car_trace_log_list($car_info['car_id']);
//            $trace_logs = M('car_trace_log')->where(array('car_id' => $car_info['car_id']))->getField('action_log');
        }
        //车牌号
        $show_info['plate_num'] = C("PLATE_PREFIX." . $car_info['plate_prefix']) . $car_info['plate_suffix'];
        //车型
        $a = new \AuctionCore\Other\Address();
        $area = $a->get_province($car_info['reg_city']);
        $show_info['reg_city'] = $area['province'] . " " . $area['city'];
        $cm = new \AuctionCore\CarResource\CarModel();
        $brand = $cm->get_model_by_id($car_info['brand_id'], 'brand');
        $series = $cm->get_model_by_id($car_info['series_id'], 'series');
        $model = $cm->get_model_by_id($car_info['model_id']);
        $show_info['model'] = $area['province'] . " " . $area['city'] . " - " . $brand['name'] . " " . $series['name'] . " " . $model['name'];
        //跟踪记录
        $show_info['action_log'] = $trace_logs;
        //渠道来源
        $carOwnerInfo = \AuctionBack\Logic\CarOwnerLogic::getCarOwnerByMap(['owner_id' => $car_info['owner_id']]);
        $show_info['comefrom'] = $carOwnerInfo['comefrom'];
        $show_from = \AuctionCore\Other\Channel::get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $show_info['order_status'] = $detail['status'];
        if (in_array($detail['status'], [10, 11, 13])) {
            $transferInfo = \AuctionBack\Logic\TransferLogic::getTransferLogInfoByOrderId($detail['order_id']);
            $show_info['transfer_to'] = $transferInfo['transfer_to'];
            $show_info['transfer_to_name'] = C("TRANSFER_TO." . $transferInfo['transfer_to']);
            $show_info['deadlinetime'] = $transferInfo['deadlinetime'];
            $show_info['mentiontime'] = $transferInfo['mentiontime'];
            $show_info['result'] = $transferInfo['result'];
        }
        $pay_status = $car_info['pay_status'];
        $pay_status_code = 0;
        $pay_status_type = 0;
        if ($pay_status == -1) {
            $pay_status_code = -1;
        } elseif ($pay_status == 1) {
            $pay_status_code = 1;
        } elseif ($pay_status == 2) {
            if ($car_info['car_source'] == 1) {    //4s店
                $pay_status_code = 2;
                $pay_status_type = 21;
            } elseif ($car_info['car_source'] == 2) {  //个人
                if ($car_info['three_in_one'] == 1) {
                    $pay_status_code = 2;
                    $pay_status_type = 22;
                } else {                                  //三证不合一待付尾款显示为已付首款（0%）
                    $pay_status_code = 2;
                    $pay_status_type = 23;
                }
            }
        } elseif ($pay_status == 3) {
            $pay_status_code = 3;
        } elseif ($pay_status == 4) {
            if ($car_info['car_source'] == 1) {        //4s店
                $pay_status_code = 2;
                $pay_status_type = 21;
            } elseif ($car_info['car_source'] == 2) { //个人
                $pay_status_code = 4;
                $pay_status_type = 21;
            }
        }
        $show_info['pay_status'] = C("ORDER_PAY_STATUS")[$pay_status_code];
        $show_info['pay_status_type'] = $pay_status_type;

        $this->assign('show', $show_info);
        $html = $this->view->fetch('OrderCheck/records');
        $this->helpJsonResult(200, 'SUCCESS', $html);
    }

    /**
     * 获取智能报价-报价队列
     */
    public function price_queue()
    {
        $order_id = I('get.id');
        $p = I('get.p');

        $price = new \AuctionCore\AuctionOrder\AutoPrice();


        $price_queue = $price->price_queue($order_id, $p);


        $this->assign('list', $price_queue['list']);
        $this->assign('page', $price_queue['page']);
        $this->display();

    }


    /**
     * 获取职能报价-报价历史
     */
    public function price_history()
    {
        $order_id = I('get.id');
        $p = I('get.p');

        $price = new \AuctionCore\AuctionOrder\AutoPrice();

        $price_history = $price->price_history($order_id, $p);

        $this->assign('list', $price_history['list']);
        $this->assign('page', $price_history['page']);
        $this->display();

    }


}
